import { User, UserModel } from '../models/user';
import db from '../common';
import redisDb from '../redis';

// const EXPRIRES_TIME = 3600;

export default class UserService {
  hello = () => {
    return new Promise(resolve => resolve('hello User'));
  };
  getUserInfo = async(ctx: any) => {
    const { name } = ctx.query;
    const redisGetRet: any = await redisDb.getObjectDate(name);
    if (redisGetRet) {
      return JSON.parse(redisGetRet);
    }
    const ret = await db.Find(UserModel, { name }, '')
    redisDb.SetObjectData(name, JSON.stringify(ret));
    return ret;
  };
  getPaginUser = async(ctx: any) => {
    let { pageSize, pageIndex, keyWords } = ctx.query;
    pageSize = parseInt(pageSize);
    pageIndex = parseInt(pageIndex);
    const conditions = {};
    if (keyWords && keyWords !== '') {
      console.log(keyWords)
      const reg = new RegExp(keyWords, 'i');
      conditions['$or'] = [
        { name: { $regex: reg } },
        { city: { $regex: reg } },
      ]
    };
    const ret: any = await db.Find(UserModel, conditions, '', {
      skip: (pageIndex - 1) * pageSize,
      limit: pageSize
    });
    ret.total = await db.FindCount(UserModel, conditions)
    return ret;
  };
  addUser = async(ctx: any) => {
    const user: User[] = ctx.request.body;
    console.log(user);
    const ret = await db.Insert<User>(UserModel, user);
    console.log(ret)
    return 'OKK'
  };
  updateUser = async(ctx: any) => {
    const user = ctx.request.body;
    console.log(user);
    const conditions = {
      _id: user._id
    }
    delete user._id;
    const ret = await db.Update(UserModel, conditions, user);
    return ret;
  };
  deleteUser = async(ctx: any) => {
    const userInfo = ctx.request.body.userInfo;
    const conditions = {
      _id: {
        $in: userInfo
      }
    }
    const ret = await db.DeleteOne(UserModel, conditions);
    return ret;
  }
}
